using BackOffice.Application.Services;
using BackOffice.Application.DTOs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Backoffice.Api.Filters;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class LogActionAttribute : ActionFilterAttribute
{
    private readonly string _actionName;
    private readonly string _description;

    public LogActionAttribute(string actionName = "", string description = "")
    {
        _actionName = actionName;
        _description = description;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var logService = context.HttpContext.RequestServices.GetService<ILogService>();
        var username = context.HttpContext.User?.Identity?.Name ?? "anonymous";
        var ipAddress = GetClientIpAddress(context.HttpContext);
        var userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString();
        var method = context.HttpContext.Request.Method;
        var path = context.HttpContext.Request.Path;

        var actionName = string.IsNullOrEmpty(_actionName) 
            ? $"{method} {path}" 
            : _actionName;

        var description = string.IsNullOrEmpty(_description) 
            ? $"{method} {path}" 
            : _description;

        try
        {
            // 记录操作开始
            var startLogDto = new LogRecordDto(
                Username: username,
                Action: $"[INFO] {actionName} - 开始",
                Description: description,
                IpAddress: ipAddress,
                UserAgent: userAgent
            );

            if (logService != null)
            {
                await logService.RecordLogAsync(startLogDto);
            }

            // 执行操作
            var result = await next();

            // 记录操作完成
            var endLogDto = new LogRecordDto(
                Username: username,
                Action: $"[INFO] {actionName} - 完成",
                Description: $"{description} - 成功",
                IpAddress: ipAddress,
                UserAgent: userAgent
            );

            if (logService != null)
            {
                await logService.RecordLogAsync(endLogDto);
            }
        }
        catch (Exception ex)
        {
            // 记录错误
            var errorLogDto = new LogRecordDto(
                Username: username,
                Action: $"[ERROR] {actionName} - 失败",
                Description: $"{description} - 错误: {ex.Message}",
                IpAddress: ipAddress,
                UserAgent: userAgent
            );

            if (logService != null)
            {
                await logService.RecordLogAsync(errorLogDto);
            }

            throw;
        }
    }

    private string GetClientIpAddress(HttpContext context)
    {
        var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Request.Headers["X-Real-IP"].FirstOrDefault();
        }
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Connection.RemoteIpAddress?.ToString();
        }
        return ip ?? "unknown";
    }
}